package com.midian.common.baiduPush;

import org.apache.log4j.Logger;

import net.sf.json.JSONObject;

import com.midian.common.baiduPush.core.log.YunLogEvent;
import com.midian.common.baiduPush.core.log.YunLogHandler;
import com.midian.common.baiduPush.push.auth.PushKeyPair;
import com.midian.common.baiduPush.push.client.BaiduPushClient;
import com.midian.common.baiduPush.push.constants.BaiduPushConstants;
import com.midian.common.baiduPush.push.exception.PushClientException;
import com.midian.common.baiduPush.push.exception.PushServerException;
import com.midian.common.baiduPush.push.model.PushMsgToAllRequest;
import com.midian.common.baiduPush.push.model.PushMsgToAllResponse;
import com.midian.common.baiduPush.push.model.PushMsgToSingleDeviceRequest;
import com.midian.common.baiduPush.push.model.PushMsgToSingleDeviceResponse;

public class AndroidPush {
	
	private static final Logger LOG = Logger.getLogger(AndroidPush.class);
	
	// 1. get apiKey and secretKey from developer console
	public static final String apiKey = "E1ntuF04XM7ThBXXsKnlY6oPVjGRIQzj";
	public static final String secretKey = "uncgnOfor1naPpWDGsG86yVtcMW5hUQQ";
	/**
	 * 全推
	 * @param msg 消息内容
	 * @throws PushClientException
	 * @throws PushServerException
	 */
	public static void pushToAll(String msg)throws PushClientException,PushServerException {
		PushKeyPair pair = new PushKeyPair(apiKey, secretKey);

		// 2. build a BaidupushClient object to access released interfaces
		BaiduPushClient pushClient = new BaiduPushClient(pair,
				BaiduPushConstants.CHANNEL_REST_URL);

		// 3. register a YunLogHandler to get detail interacting information
		// in this request.
		pushClient.setChannelLogHandler(new YunLogHandler() {
			@Override
			public void onHandle(YunLogEvent event) {
				LOG.info(event.getMessage());
			}
		});

		try {
			// 4. specify request arguments
			PushMsgToAllRequest request = new PushMsgToAllRequest()
					.addMsgExpires(new Integer(3600))
					.addMessageType(1) // 1：通知,0:透传消息. 默认为0 注：IOS只有通知.
					.addMessage(msg) //添加透传消息
					.addSendTime(System.currentTimeMillis() / 1000 + 120) // 设置定时推送时间，必需超过当前时间一分钟，单位秒.实例2分钟后推送
					.addDeviceType(3);
			// 5. http request
			PushMsgToAllResponse response = pushClient.pushMsgToAll(request);
			// Http请求结果解析打印
			LOG.info("msgId: " + response.getMsgId() + ",sendTime: "
					+ response.getSendTime() + ",timerId: "
					+ response.getTimerId());
		} catch (PushClientException e) {
			if (BaiduPushConstants.ERROROPTTYPE) {
				throw e;
			} else {
				e.printStackTrace();
			}
		} catch (PushServerException e) {
			if (BaiduPushConstants.ERROROPTTYPE) {
				throw e;
			} else {
				LOG.info(String.format(
						"requestId: %d, errorCode: %d, errorMessage: %s",
						e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
			}
		}
	}
	/**
	 * 单推，单独推动某个设备
	 * @param title 标题
	 * @param description 描述
	 * @param channelId
	 * @throws PushClientException
	 * @throws PushServerException
	 */
	public static void pushToSingleDevice(String title,String description,String channelId)throws PushClientException,PushServerException {
		PushKeyPair pair = new PushKeyPair(apiKey, secretKey);
		// 2. build a BaidupushClient object to access released interfaces
		BaiduPushClient pushClient = new BaiduPushClient(pair,BaiduPushConstants.CHANNEL_REST_URL);
		// 3. register a YunLogHandler to get detail interacting information
		// in this request.
		pushClient.setChannelLogHandler(new YunLogHandler() {
			@Override
			public void onHandle(YunLogEvent event) {
				LOG.info(event.getMessage());//URL:[http://api.tuisong.baidu.com/rest/3.0/push/single_device]
				//params:[apikey=Ke2bk5WK8dgLhsZqednaWdna&channel_id=3869333720977292454&device_type=3&msg=%7B%22title%22%3A%22%E8%AE%B8%E6%B4%8B%22%2C%22description%22%3A%22%E8%AE%B8%E6%B4%8B%EF%BC%8C%E5%91%BC%E5%8F%AB%E8%AE%B8%E6%B4%8B%22%2C%22notification_builder_id%22%3A0%2C%22notification_basic_style%22%3A4%2C%22open_type%22%3A1%2C%22url%22%3A%22http%3A%2F%2Fpush.baidu.com%22%2C%22custom_content%22%3A%7B%22key%22%3A%22value%22%7D%7D&msg_expires=3600&msg_type=1&sign=890c0f3c4cea5edca8ab602d75d59b08&timestamp=1435660918]
				//HttpStatusCode:[200]
				//Response:[{"request_id":2785343942,"response_params":{"msg_id":"5674622019310040987","send_time":1435660918}}]
			}
		});
		try {
			// 4. specify request arguments
			//创建 Android的通知
			JSONObject notification = new JSONObject();
			notification.put("title", title);
			notification.put("description",description);
			notification.put("notification_builder_id", 0);
			notification.put("notification_basic_style", 4);
			notification.put("open_type", 2);
			notification.put("url", "http://push.baidu.com");
			JSONObject jsonCustormCont = new JSONObject();
			jsonCustormCont.put("key", "value"); //自定义内容，key-value
			notification.put("custom_content", jsonCustormCont);

			PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest().addChannelId(channelId)
					.addMsgExpires(new Integer(3600)) // message有效时间
					.addMessageType(1) // 1：通知,0:透传消息. 默认为0 注：IOS只有通知.
					.addMessage(notification.toString())
					.addDeviceType(3);// deviceType => 3:android, 4:ios
			// 5. http request
			PushMsgToSingleDeviceResponse response = pushClient.pushMsgToSingleDevice(request);
			// Http请求结果解析打印
			//LOG.info("msgId: " + response.getMsgId() + ",sendTime: "+ response.getSendTime());//msgId: 5674622019310040987,sendTime: 1435660918
		} catch (PushClientException e) {
			/*
			 * ERROROPTTYPE 用于设置异常的处理方式 -- 抛出异常和捕获异常,'true' 表示抛出, 'false' 表示捕获。
			 */
			if (BaiduPushConstants.ERROROPTTYPE) {
				throw e;
			} else {
				e.printStackTrace();
			}
		} catch (PushServerException e) {
			if (BaiduPushConstants.ERROROPTTYPE) {
				throw e;
			} else {
				LOG.info(String.format("requestId: %d, errorCode: %d, errorMessage: %s",e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
			}
		}
	}
//	public static void main(String[] args) {
//		try {
//			pushToSingleDevice("许洋","许洋，呼叫许洋","3869333720977292454");
//		} catch (PushClientException e) {
//		
//			e.printStackTrace();
//		} catch (PushServerException e) {
//			e.printStackTrace();
//		}
//		
//	}

}
